<?php
namespace App\Listener;

use App\Event\UserChat;
use Hyperf\Utils\Codec\Json;
use Hyperf\Event\Contract\ListenerInterface;
use Hyperf\Di\Annotation\Inject;
use Psr\Container\ContainerInterface;
use Hyperf\Redis\RedisFactory;
use Hyperf\DbConnection\Db;

class UserChatListener implements ListenerInterface
{
    /**
     * @Inject
     * @var ContainerInterface
     */
    protected $container;

    public function listen(): array
    {
        // 返回一个该监听器要监听的事件数组，可以同时监听多个事件
        return [
            UserChat::class,
        ];
    }

    /**
     * 聊天逻辑处理
     */
    public function process(object $event)
    {
        // 事件触发后该监听器要执行的代码写在这里，比如该示例下的发送用户注册成功短信等
        // 直接访问 $event 的 user 属性获得事件触发时传递的参数值
        $user = $event->user;
        $data = $event->data;
        $message = Json::decode($data);
        $redis = $this->container->get(RedisFactory::class)->get('chat');
        $to_id = $redis->get((string)$message['to_id']);
        //插入聊天记录表
        if ($message['msg_type'] == 2) {
            $message['message'] = $message['img_id'] ?? 0;
        }
        $nowTime = time();
        Db::table('lb_chat_logs')->insert([
            'from_id' => $user->id,
            'to_id' => $message['to_id'],
            'msg' => $message['message'],
            'msg_type' => $message['msg_type'],
            'create_time' => $nowTime,
            'update_time' => $nowTime,
        ]);
        $io = \Hyperf\Utils\ApplicationContext::getContainer()->get(\Hyperf\SocketIOServer\SocketIO::class);
        if ($to_id) {
            $io->to($to_id)->emit('broadcastingListen', $data);
        } else {
            $from_id = $redis->get((string)$user->id);
            $io->to($from_id)->emit('notice', "对方不在线");
        }
    }
}
